package com.epam.qanda.web.servlet.logged;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.epam.qanda.db.model.User;
import com.epam.qanda.db.service.UserService;

public class AccountUpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = Logger.getLogger("stdout");

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserService userService = new UserService();
		User user = (User) request.getSession().getAttribute("user");
		String inputLogin = request.getParameter("inputLogin");
		String inputOldPassword = request.getParameter("inputOldPassword");
		String inputPassword = request.getParameter("inputPassword");
		String inputConfirmPassword = request.getParameter("inputConfirmPassword");
		String inputEmail = request.getParameter("inputEmail");
		String inputFName = request.getParameter("inputFName");
		String inputLName = request.getParameter("inputLName");
		if (inputLogin != null && !inputLogin.isEmpty() && !inputLogin.equals(user.getLogin())) {
			user.setLogin(inputLogin);
		}
		if (inputOldPassword != null && !inputOldPassword.isEmpty()) {
			// TODO add md5 here
			if (inputOldPassword.equals(user.getPassword())) {
				if (inputPassword != null && !inputPassword.isEmpty()
						&& inputConfirmPassword != null
						&& inputConfirmPassword.equals(inputPassword)) {
					user.setPassword(inputPassword);
				}
			}
		}
		if (inputEmail != null && !inputEmail.isEmpty()) {
			user.setEmail(inputEmail);
		}
		if (inputFName != null && !inputFName.isEmpty()) {
			user.setfName(inputFName);
		}
		if (inputLName != null && !inputLName.isEmpty()) {
			user.setlName(inputLName);
		}
		userService.update(user);
		LOG.info("Changing is done");
		response.sendRedirect(request.getHeader("referer"));
	}
}
